# coding:utf-8
class Admin::TablesController < AdminController
  
  respond_to :html, :json

  set_tab :developers
  set_tab :tables, :sub_nav
  before_filter :setup, only: [:index]

  def index
    params[:tables] ||= {}
    @models = get_models
    if params[:tables][:name].blank?
      @error = '请选择表'
    else
      model = params[:tables][:name].constantize
      @fields = model.attribute_names

      # if query for field
      if params[:tables][:field].present? && params[:tables][:value].present?
        # check whether the field exists
        if @fields.include?(params[:tables][:field])
          is_fuzzy = params[:tables][:value].start_with?('%') || params[:tables][:value].end_with?('%')
          operator = is_fuzzy ? 'like' : '='
          model = model.where("#{params[:tables][:field]} #{operator} ?", params[:tables][:value])
        else
          @tip = '未找到' + params[:tables][:field] + ',已忽略,可用列:' + @fields.join(',')
        end
      end

      # if query for start date
      if params[:tables][:start_date].present?
        model = model.where(["created_at >= ?", params[:tables][:start_date]])
      end
      if params[:tables][:end_date].present?
        model = model.where(["created_at < ?", 
          1.days.since(Time.zone.parse(params[:tables][:end_date])).strftime("%Y-%m-%d")])
      end
      @rows = model.order('id desc').page(params[:page])
      
      begin
        if @rows.empty?
          @error = '未找到记录'
        end
      rescue ActiveRecord::StatementInvalid => e
        @error = '数据库查询错误' + e.message
      end
    end
  end

  def destroy
    model = params[:table].constantize
    @model = model.find params[:id]
    @model.destroy
  end

  private 
  # get all models: first load all models and then reject which doesn't has tables
  def get_models
    Dir.glob(Rails.root.join('app/models/*.rb')).each { |file| require file }
    ActiveRecord::Base.descendants.select { |model| model.table_exists? }
  end

  def setup
    @ways = ["日志管理","数据库"]
    @left_panel = "layouts/developer_left_panel"
  end
end